<template>

    <div style="border-style:groove;border-width: 2px;margin-bottom: 20px;height: 100px;">

        <el-form :inline="true" :model="formInline" class="demo-form-inline" style="margin-top: 30px;">
            <el-form-item label="申请人">
                <el-input v-model="formInline.UserName" placeholder="" clearable />
            </el-form-item>
            <el-form-item label="审批状态">
                <el-select v-model="formInline.state" placeholder="" style="width: 120px;">
                    <el-option label="请选择" value="" />
                    <el-option label="已审批" :value="true" />
                    <el-option label="未审批" :value="false" />
                </el-select>
            </el-form-item>
            <el-form-item label="时间">
                <el-col :span="11">
                    <el-date-picker v-model="formInline.BeginTime" type="date" placeholder="开始时间" style="width: 100%" />
                </el-col>
                <el-col :span="2" class="text-center">
                    <span class="text-gray-500">-</span>
                </el-col>
                <el-col :span="11">
                    <el-date-picker v-model="formInline.EndTime" type="date" placeholder="结束时间" style="width: 100%" />
                </el-col>
            </el-form-item>


            <el-form-item>
                <el-button type="primary" @click="Show">查询</el-button>
            </el-form-item>
        </el-form>
    </div>

    <el-button type="success" plain @click="OpenAddUser">
        新增
    </el-button>

    <div style="border-style:groove;border-width: 2px;margin-bottom: 20px;height: 550px;">
        <el-table :data="tableData" border style="width: 100%;height: 500px;">
            <el-table-column type="index" label="编号" />
            <el-table-column prop="userName" label="姓名" />
            <el-table-column prop="deptName" label="部门" />
            <el-table-column prop="typeEnumsName" label="请假类别" />
            <el-table-column prop="leaveTIme" label="请假时间" width="200px">
                <template v-slot="scoped">
                    <text>{{ scoped.row.leaveTIme.toString().substring(0, 10) }}</text>至 <text>{{
                        scoped.row.reportTIme.toString().substring(0, 10) }}</text>
                </template>
            </el-table-column>
            <el-table-column prop="sumTime" label="总工时" />
            <el-table-column prop="reportTIme" label="报道时间">
                <template v-slot="scoped">
                    {{ moment(scoped.row.reportTIme).format("YYYY-MM-DD") }}
                </template>
            </el-table-column>
            <el-table-column prop="typeEnumsName" label="请假事由" />
            <el-table-column prop="deptBoos" label="部门领导" />
            <el-table-column prop="state" label="审核状态">
                <template v-slot="scoped">
                    {{ scoped.row.state == false ? "待审核" : "已审核" }}
                </template>
            </el-table-column>
            <el-table-column prop="isResult" label="审核结果" />
            <el-table-column prop="resultDesc" label="审核原因" />
            <el-table-column prop="createTime" label="创建日期" width="100px">
                <template v-slot="scoped">
                    {{ moment(scoped.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200px">
                <template v-slot="scoped">
                    <el-button type="danger" v-show="scoped.row.userId == ruleForm.userId && scoped.row.state == false"
                        plain @click="Del(scoped.row.id)">删除</el-button>
                    <el-button type="primary" v-show="scoped.row.userId == ruleForm.userId && scoped.row.state == false"
                        plain @click="openUpdata(scoped.row)">修改</el-button>
                    <el-button type="primary"
                        v-show="scoped.row.deptBoos == ruleForm.userName && scoped.row.state == false" plain
                        @click="openUpState(scoped.row)">审批</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="demo-pagination-block">


            <el-pagination v-model:current-page="PageData.PageIndex" v-model:page-size="PageData.PageSize"
                :page-sizes="[15, 20, 25, 30]" :background="true
                    " layout="total, sizes, prev, pager, next, jumper" :total="PageData.count" prev-text="上一页"
                next-text="下一页" />
        </div>
    </div>




    <!-- 新增 -->
    <el-dialog v-model="dialogFormVisible" title="新增" width="500">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="用户名" prop="userName">
                <el-input v-model="ruleForm.userName" />
            </el-form-item>
            <el-form-item label="部门" prop="deptId">
                <el-select v-model="ruleForm.deptId" placeholder="" style="width: 120px;">
                    <el-option label="请选择" value="0" />
                    <el-option v-for="item in DeptData" :label="item.deptName" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="请假类别" prop="typeEnums1">
                <el-checkbox-group v-model="ruleForm.typeEnums1">
                    <!--                     <el-checkbox v-for="item in ENumTypeData" :value="item.key" name="type">
                        {{ item.value }}
                    </el-checkbox> -->

                    <el-radio-group v-model="ruleForm.typeEnums1">
                        <el-radio v-for="item in ENumTypeData" :value="item.key" size="large">{{ item.value }}
                        </el-radio>
                    </el-radio-group>
                </el-checkbox-group>

            </el-form-item>
            <el-form-item label="请假时间" prop="leaveTIme">


                <el-col :span="11">
                    <el-date-picker v-model="ruleForm.leaveTIme" type="datetime" placeholder="开始时间" style="width: 100%"
                        format="YYYY-MM-DD HH:mm:ss" />
                </el-col>
                <el-col :span="2" class="text-center">
                    <span class="text-gray-500">-至</span>
                </el-col>
                <el-col :span="11">
                    <el-date-picker v-model="ruleForm.reportTIme" type="datetime" placeholder="结束时间" style="width: 100%"
                        format="YYYY-MM-DD HH:mm:ss" />
                </el-col>
                <p>{{ timeDifference }}</p>
                <el-form-item label="报道时间" prop="reportTIme">
                    <el-col :span="11">
                        <el-date-picker v-model="ruleForm.reportTIme" type="datetime" placeholder="结束时间"
                            style="width: 200px" format="YYYY-MM-DD HH:mm:ss" />
                    </el-col>
                </el-form-item>
            </el-form-item>
            <el-form-item label="请假事由" prop="desc">
                <el-input v-model="ruleForm.desc" type="textarea" />
            </el-form-item>

            <el-form-item label="部门领导">
                <el-input v-model="ruleForm.deptBoos" type="text" disabled />
            </el-form-item>



            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    保存
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <!-- 修改 -->
    <el-dialog v-model="Update" title="修改" width="500">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="用户名" prop="userName">
                <el-input v-model="ruleForm.userName" />
            </el-form-item>
            <el-form-item label="部门" prop="deptId">
                <el-select v-model="ruleForm.deptId" placeholder="" style="width: 120px;">
                    <el-option label="请选择" value="0" />
                    <el-option v-for="item in DeptData" :label="item.deptName" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="请假类别" prop="typeEnums1">
                <el-checkbox-group v-model="ruleForm.typeEnums1">
                    <el-checkbox v-for="item in ENumTypeData" :value="item.key" name="type">
                        {{ item.value }}
                    </el-checkbox>

                </el-checkbox-group>

            </el-form-item>
            <el-form-item label="请假时间" prop="userName">


                <el-col :span="11">
                    <el-date-picker v-model="ruleForm.leaveTIme" type="datetime" placeholder="开始时间" style="width: 100%"
                        format="YYYY-MM-DD HH:mm:ss" />
                </el-col>
                <el-col :span="2" class="text-center">
                    <span class="text-gray-500">-至</span>
                </el-col>
                <el-col :span="11">
                    <el-date-picker v-model="ruleForm.reportTIme" type="datetime" placeholder="结束时间" style="width: 100%"
                        format="YYYY-MM-DD HH:mm:ss" />
                </el-col>
                <p>{{ timeDifference }}</p>
                <el-form-item label="报道时间">
                    <el-col :span="11">
                        <el-date-picker v-model="ruleForm.reportTIme" type="datetime" placeholder="结束时间"
                            style="width: 200px" format="YYYY-MM-DD HH:mm:ss" />
                    </el-col>
                </el-form-item>
            </el-form-item>
            <el-form-item label="请假事由" prop="userName">
                <el-input v-model="ruleForm.desc" type="textarea" />
            </el-form-item>

            <el-form-item label="部门领导">
                <el-input v-model="ruleForm.deptBoos" type="text" disabled />
            </el-form-item>



            <el-form-item>
                <el-button type="primary" @click="UpdatesubmitForm(ruleFormRef)">
                    保存
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>


    <!--  审批 -->
    <el-dialog v-model="OpenBoosUpState" title="审批" width="500">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="用户名">
                <el-input v-model="ruleForm.userName" disabled />
            </el-form-item>
            <el-form-item label="部门">
                <el-select v-model="ruleForm.deptId" placeholder="" style="width: 120px;" disabled>
                    <el-option label="请选择" value="0" />
                    <el-option v-for="item in DeptData" :label="item.deptName" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="请假类别">
                <el-input v-model="ruleForm.typeEnumsName" disabled />
            </el-form-item>
            <el-form-item label="请假时间">


                <el-col :span="11">
                    <el-date-picker v-model="ruleForm.leaveTIme" type="datetime" placeholder="开始时间" style="width: 100%"
                        format="YYYY-MM-DD HH:mm:ss" disabled />
                </el-col>
                <el-col :span="2" class="text-center">
                    <span class="text-gray-500">-至</span>
                </el-col>
                <el-col :span="11">
                    <el-date-picker v-model="ruleForm.reportTIme" type="datetime" placeholder="结束时间" style="width: 100%"
                        format="YYYY-MM-DD HH:mm:ss" disabled />
                </el-col>
                <p>{{ timeDifference }}</p>
                <el-form-item label="报道时间">
                    <el-col :span="11">
                        <el-date-picker v-model="ruleForm.reportTIme" type="datetime" placeholder="结束时间"
                            style="width: 200px" format="YYYY-MM-DD HH:mm:ss" disabled />
                    </el-col>
                </el-form-item>
            </el-form-item>
            <el-form-item label="请假事由">
                <el-input v-model="ruleForm.desc" type="textarea" disabled />
            </el-form-item>

            <el-form-item label="审核" prop="isResult">
                <el-radio-group v-model="ruleForm.isResult">
                    <el-radio value="同意" @click="BoosUpStateData.OPenIsRresultDesc = false" size="large">同意</el-radio>
                    <el-radio value="驳回" @click="BoosUpStateData.OPenIsRresultDesc = true" size="large">驳回</el-radio>
                    <el-form-item label="原因" prop="resultDesc" v-if="BoosUpStateData.OPenIsRresultDesc == true">
                        <el-input v-model="ruleForm.resultDesc" type="textarea" />
                    </el-form-item>
                </el-radio-group>


            </el-form-item>



            <el-form-item>
                <el-button type="primary" @click="BoosUpState(ruleFormRef)">
                    保存
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>



</template>

<script lang="ts" setup>
import { readB } from '@/http/axiosHelper'
import { onMounted, ref, watch, reactive, computed } from 'vue';
import moment from 'moment';

const dialogFormVisible = ref(false)
const OpenBoosUpState = ref(false)
const Update = ref(false)
const formLabelWidth = '140px'

//查询对象
const formInline = reactive({
    UserName: '',
    state: '',
    BeginTime: '',
    EndTime: ''
})



const tableData = ref([]);
const PageData = ref({
    PageIndex: 1,
    PageSize: 15,
    count: 0,
})



//查询申请列表
const Show = () => {
    console.log(formInline.BeginTime);
    console.log(formInline.EndTime);

    readB.get("/api/Leave/QueryLeave", {
        params: {
            UserId: 3,
            PageIndex: PageData.value.PageIndex,
            PageSize: PageData.value.PageSize,
            UserName: formInline.UserName,
            state: formInline.state,
            BeginTime: formInline.BeginTime,
            EndTime: formInline.EndTime
        }
    })
        .then(res => {
            if (res.data.code == 200) {
                tableData.value = res.data.pageData;
                PageData.value.count = res.data.count;

            }
        })
}


const openUpdata = async (row: any) => {
    GetAddressSheng();
    GetENumType();
    Object.assign(ruleForm, row);
    ruleForm.typeEnums1 = [row.typeEnums]
    ruleForm.leaveTIme = (new Date(row.leaveTIme))
    ruleForm.reportTIme = (new Date(row.reportTIme))

    Update.value = true;
}

//自动计算时间差

const timeDifference = computed(() => {
    const diffMs = ruleForm.reportTIme - ruleForm.leaveTIme;

    const totalHours = diffMs / (1000 * 60 * 60);

    const days = Math.floor(totalHours / 24);
    const hours = (totalHours % 24).toFixed(2);

    /*  // 按每8小时为一个工作日计算
     const workDays = Math.ceil(totalHours / 8); // 向上取整
     const totalLeaveHours = workDays * 8; */


    if (days >= 1) {
        ruleForm.sumTime = days * 8;
    }
    else {
        ruleForm.sumTime = 8;
    }

    console.log(ruleForm.sumTime);

    return `共计 ${days} 天 ${hours} 小时`;
});


//-----添加

import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { dataType } from 'element-plus/es/components/table-v2/src/common.mjs';






const ruleFormRef = ref<FormInstance>()
const ruleForm: any = reactive({
    "userId": localStorage.getItem("id"),
    "userName": localStorage.getItem("userName"),
    "deptId": Number(localStorage.getItem("deptId")),
    "typeEnums1": [],
    "typeEnums": "",
    "leaveTIme": "",
    "reportTIme": "",
    "desc": "",
    "deptBoos": "",
    typeEnumsName: "",
    "id": 0,
    "isResult": "",
    "resultDesc": "",
    "sumTime": 0
})



const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
    userName: [
        { required: true, message: '用户名不能为空', trigger: 'blur' },

    ],
    isResult: [
        { required: true, message: '审批结果不能为空', trigger: 'blur' },
    ],
    resultDesc: [
        { required: true, message: '审批原因不能为空', trigger: 'blur' },
    ],

    typeEnums1: [
        { required: true, message: '请假类别不能为空', trigger: 'blur' },
        { pattern: /^\d$/, message: '请假类别只能选择一个', trigger: 'blur' },
    ],
    leaveTIme: [
        { required: true, message: '请假时间不能为空', trigger: 'blur' },
        /*  {
             validator: (rule, value, callback) => {
                 const startDate = rules.reportTIme
                 if () {
 
                 }
             }
         } */
    ],
    reportTIme: [
        { required: true, message: '报道时间不能为空', trigger: 'blur' },
    ],
    desc: [
        { pattern: /^[\u4e00-\u9fa5\uff00-\uffef]{0,140}$/, message: '详情地址必须为中文且不超过140个字符', trigger: 'blur' }
    ]

})




const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {

            ruleForm.typeEnums = Number(ruleForm.typeEnums1.toString());
            console.log(ruleForm);
            readB.post("/api/Leave/AddLeave", ruleForm)
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.msg);
                        dialogFormVisible.value = false
                        Show();
                    }
                    else {
                        ElMessage.error(res.data.msg);
                    }
                })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const UpdatesubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log(ruleForm);
            ruleForm.typeEnums = Number(ruleForm.typeEnums1.toString());
            readB.post("/api/Leave/UpDataLeave", ruleForm)
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.msg);
                        Update.value = false
                        Show();

                    }
                    else {
                        ElMessage.error(res.data.msg);
                    }
                })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))

const OpenAddUser = () => {
    ruleForm.leaveTIme = ""
    ruleForm.typeEnums = []
    ruleForm.reportTIme = ""
    ruleForm.desc = ""

    GetAddressSheng();
    GetENumType();
    GetDeptBoosName();


    dialogFormVisible.value = true


}

const DeptData = ref([{
    deptName: "",
    id: ""
}])
const GetAddressSheng = () => {
    readB.get("/api/Leave/GetDept")
        .then(res => {
            DeptData.value = res.data.data
        })
}

const ENumTypeData = ref([{
    key: "",
    value: ""
}])
const GetENumType = () => {
    readB.get("/api/Leave/GetEnumType")
        .then(res => {
            ENumTypeData.value = res.data
        })
}



const GetDeptBoosName = () => {
    readB.get("/api/Leave/GetDeptName", {
        params: {
            Id: ruleForm.deptId
        }
    })
        .then(res => {
            ruleForm.deptBoos = res.data.data
        })
}


onMounted(() => {
    Show();

})

watch(() => { PageData.value.PageIndex, PageData.value.PageSize }, () => {
    Show();
}, {
    deep: true
})




import { ElMessageBox } from 'element-plus'
import { ru } from 'element-plus/es/locales.mjs';
const Del = (id: any) => {
    ElMessageBox.confirm(
        '确认删除么?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            readB.post("/api/Leave/Handle", null, {
                params: {
                    Id: id
                }
            })
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.msg);
                        Show();
                    }
                    else {
                        ElMessage.error(res.data.msg);
                    }
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
}

//审批
const openUpState = (row: any) => {
    GetAddressSheng();


    ruleForm.typeEnumsName = row.typeEnumsName
    ruleForm.leaveTIme = (new Date(row.leaveTIme))
    ruleForm.reportTIme = (new Date(row.reportTIme))
    ruleForm.desc = row.desc
    ruleForm.deptBoos = row.deptBoos

    ruleForm.id = row.id
    OpenBoosUpState.value = true;



    /*    "userId": localStorage.getItem("id"),
       "userName": localStorage.getItem("userName"),
       "deptId": Number(localStorage.getItem("deptId")),
       "typeEnums1": [],
       "typeEnums": "",
       "leaveTIme": "",
       "leaveTIme1": "",
       "reportTIme": "",
       "reportTIme1": "",
       "desc": "",
       "deptBoos": "" */
}

const BoosUpStateData = ref({
    OPenIsRresultDesc: false
})




const BoosUpState = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {


            console.log(ruleForm);
            readB.post("/api/Leave/BoosUp", ruleForm)
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.msg);
                        OpenBoosUpState.value = false
                        Show();
                    }
                    else {
                        ElMessage.error(res.data.msg);
                    }
                })
        } else {
            console.log('error submit!', fields)
        }
    })
}


</script>